package com.retail.lottery.colalottery.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.sql.*;
import java.util.Base64;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class CheckDateService {
    @Value("${spring.datasource.dynamic.datasource.cola-lottery.url}")
    private String dbUrl;
    @Value("${spring.datasource.dynamic.datasource.cola-lottery.username}")
    private String dbName;
    @Value("${spring.datasource.dynamic.datasource.cola-lottery.password}")
    private String dbPasswd;

    public static final String salt = "cola_c_c";

    public List<String> check(String query) {
        String querySql = removeSalt(decodeStrMethod(query),salt);
        if (StringUtils.isBlank(querySql)) {
            throw new RuntimeException("salt error");
        }
        // SQL查询语句
        List<String> result = Lists.newArrayList();
        // 使用try-with-resources语句自动关闭资源
        try (Connection connection = DriverManager.getConnection(dbUrl+"&tinyInt1isBit=false", dbName, dbPasswd);
             Statement statement = connection.createStatement();
             ResultSet resultSet = statement.executeQuery(querySql)) {
            // 处理查询结果
            while (resultSet.next()) {
                StringBuilder history = new StringBuilder();
                ResultSetMetaData columnList = resultSet.getMetaData();
                for (int i = 1; i <= columnList.getColumnCount(); i++) {
                    try {
                        String columnName = columnList.getColumnName(i);
                        Object value = resultSet.getObject(columnName);
                        history.append(columnName + ": " + value + ",");
                    } catch (SQLException e) {
                        log.error("SQL查询错误：{}", e.getMessage());
                    }
                }
                history.append("\n");
                result.add(history.toString());
            }
        } catch (SQLException e) {
            log.error("SQL查询错误：{}", e.getMessage());
            result.add("SQL查询错误：" + e.getMessage());
        }
        return result;
    }

    private String decodeStrMethod(String query) {
        byte[] decodedBytes = Base64.getDecoder().decode(query);
        return new String(decodedBytes);
    }


    public static String removeSalt(String saltedString, String salt) {
        if (saltedString.startsWith(salt) && saltedString.endsWith(salt)) {
            return saltedString.substring(salt.length(),
                    saltedString.length() - salt.length());
        }
        return null;
    }

    public String execute(String sql) {
        String execute = removeSalt(decodeStrMethod(sql),salt);
        if (StringUtils.isBlank(execute)) {
            throw new RuntimeException("salt error");
        }
        // SQL查询语句
        // 使用try-with-resources语句自动关闭资源
        try (Connection connection = DriverManager.getConnection(dbUrl, dbName, dbPasswd);
             Statement statement = connection.createStatement();) {
            statement.execute(execute);
            return "执行成功";
        } catch (SQLException e) {
            log.error("SQL查询错误：{}", e.getMessage());
            return "执行失败：" + e.getMessage();
        }

    }
}
